<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java,网络编程," />





  <link rel="alternate" href="/atom.xml" title="Hfbin Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="Netty最佳实战数据通信  1 分析&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;我们需要了解下在真正项目应用中如何去考虚Netty的使用，大体上对于一参数设置都是根据服务器性能决定的。这个不是最主要的。 &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;我们要考虑的问题是两台机器（甚至多台）使用Netty的怎样进行通信，我把他分为三种： &amp;nbs">
<meta name="keywords" content="java,网络编程">
<meta property="og:type" content="article">
<meta property="og:title" content="java网络编程之Netty实战数据通信（七）">
<meta property="og:url" content="http://yoursite.com/2017/11/27/java网络编程之Netty实战数据通信（七）/index.html">
<meta property="og:site_name" content="Hfbin Blog">
<meta property="og:description" content="Netty最佳实战数据通信  1 分析&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;我们需要了解下在真正项目应用中如何去考虚Netty的使用，大体上对于一参数设置都是根据服务器性能决定的。这个不是最主要的。 &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;我们要考虑的问题是两台机器（甚至多台）使用Netty的怎样进行通信，我把他分为三种： &amp;nbs">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://img.blog.csdn.net/20171127004448326?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzM1MjQxNTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171127004459063?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzM1MjQxNTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://img.blog.csdn.net/20171127004512265?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzM1MjQxNTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:updated_time" content="2018-01-06T06:11:04.074Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java网络编程之Netty实战数据通信（七）">
<meta name="twitter:description" content="Netty最佳实战数据通信  1 分析&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;我们需要了解下在真正项目应用中如何去考虚Netty的使用，大体上对于一参数设置都是根据服务器性能决定的。这个不是最主要的。 &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;我们要考虑的问题是两台机器（甚至多台）使用Netty的怎样进行通信，我把他分为三种： &amp;nbs">
<meta name="twitter:image" content="http://img.blog.csdn.net/20171127004448326?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzM1MjQxNTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'FQWD7RL0XS',
      apiKey: 'ad0b6762f0b7721176ce7c215ba85c58',
      indexName: 'hfbin',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>

<script>
    (function(){
        if(''){
            if (prompt('该文章博主已加密') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>


  <link rel="canonical" href="http://yoursite.com/2017/11/27/java网络编程之Netty实战数据通信（七）/"/>

    <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
	<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">
<style>
    .pace .pace-progress {
        background: #1E92FB; /*进度条颜色*/
        height: 3px;
    }
    .pace .pace-progress-inner {
         box-shadow: 0 0 10px #1E92FB, 0 0 5px     #1E92FB; /*阴影颜色*/
    }
    .pace .pace-activity {
        border-top-color: #1E92FB;    /*上边框颜色*/
        border-left-color: #1E92FB;    /*左边框颜色*/
    }
</style>

	


  <title>java网络编程之Netty实战数据通信（七） | Hfbin Blog</title>
  












  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1266987503&web_id=1266987503" language="JavaScript"></script>
  </div>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

 
    

  
  
  
  <link rel="stylesheet" href="/lib/algolia-instant-search/instantsearch.min.css">

  
  
  <script src="/lib/algolia-instant-search/instantsearch.min.js"></script>
  

  <script type="text/javascript" src="/js/src/algolia.js?v=5.1.2"></script>

  
  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"></span>
        <span class="site-title">Hfbin Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">My friend promised me to go if I had the road</p>
      
  </div>

  <div class="site-nav-toggle" style="position: absolute; float: left; ">
    <button>
      <span class="btn-bar" style="background: #fff;"></span>
      <span class="btn-bar" style="background: #fff;"></span>
      <span class="btn-bar" style="background: #fff;"></span>
    </button>
  </div>
</div>

<nav class="site-nav" >
  <!-- set hasSearch = theme.swiftype_key || theme.algolia_search.enable || theme.tinysou_Key || theme.local_search.enable % -->
  	


  
    <ul id="menu" class="menu" >
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
			 <!-- 增加下面语句 -->
		  
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  
  <div class="algolia-popup popup search-popup">
    <div class="algolia-search">
      <div class="algolia-search-input-icon">
        <i class="fa fa-search"></i>
      </div>
      <div class="algolia-search-input" id="algolia-search-input"></div>
    </div>

    <div class="algolia-results">
      <div id="algolia-stats"></div>
      <div id="algolia-hits"></div>
      <div id="algolia-pagination" class="algolia-pagination"></div>
    </div>

    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>




    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/11/27/java网络编程之Netty实战数据通信（七）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="HuangFuBin">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/26451830?s=400&u=fac2b4c7903b3ad1210b530e2d18e42fcb410b0a&v=4">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hfbin Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">java网络编程之Netty实战数据通信（七）</h1>
        

        <div class="post-meta">
			 
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-27T01:01:11+08:00">
                2017-11-27
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/网络编程/" itemprop="url" rel="index">
                    <span itemprop="name">网络编程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2017/11/27/java网络编程之Netty实战数据通信（七）/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2017/11/27/java网络编程之Netty实战数据通信（七）/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3>Netty最佳实战数据通信</h3>

<h4 id="1-分析"><a href="#1-分析" class="headerlink" title="1 分析"></a><strong>1 分析</strong></h4><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;我们需要了解下在真正项目应用中如何去考虚Netty的使用，大体上对于一参数设置都是根据服务器性能决定的。这个不是最主要的。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;我们要考虑的问题是两台机器（甚至多台）使用Netty的怎样进行通信，我把他分为三种：</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;第一种，使用长连接通道不断开的形式进行通信，也就是服务器和客户端的通道一直处于开启状态，如果服务器性能足够好，并且我们的客户端数量也比较少的情况下，我还是推荐这种方式的。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;第二种，一次性批量提交数据，采用短连接方式。也就是我们会把数据保存在本地临时缓冲区或者临时表里，当达到临界值时进行一次性批量提交。又或者根据定时任务轮询提交，这种情况弊端是做不到实时性传输，在对实时性不高的应用程序中可以推荐使用。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;第三种，我们可以使用一种特殊的长连接，在指定某一时间之内，服务器与某台客户端没有任何通信，则断开连接。下次连接则是客户端向服务器发送请求的时候，再次立连接。但是这种模式我们要考虑2个因素：</p>
<p>1、如何在超时（即服务器和客户端没有任何通信）后关闭通道？关闭通道后我们又如何再次建立连接？</p>
<p>2、客户端宕机时，我们无需考虑，下次客户端重启之后我们就可以与服务器建立连接，但是服务器宕机时，我们的客户端如何与服务器进行连接呢？</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;好到这这三种场景都描述了一个遍，再简单的来说一下。第一种，主要你的服务器性能够好，ok你可以采取第一种完全没问题；第二种，感觉也没什么毛病，但是做不到实时性；第三种，个人强烈建议使用第三种，我会用一个小小案例来说明，需要考虑的因素，等我把案例讲完了也许你就懂如何解决了，当然如果你会了第三个，第一个也就不算什么难事了，就相当于我们刚开始学的HelloWorld案例一样，好说了那么多废话，在这就不BB了，直接上案例，注意这里只拿第三种来说明：</p>
<h4 id="2-案例"><a href="#2-案例" class="headerlink" title="2 案例"></a><strong>2 案例</strong></h4><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;在讲解案例之前先说一下，这个案例用到JBoss Marshalling编解码框架，不了解编解码技术的可以看我上一篇文章。说实话，如果你看过上一篇文章，这个案例就相当于上一篇文章的更改版，只是在客户端这里做了一些修改。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;需要的jar包有 &nbsp;&nbsp;1、netty  &nbsp;&nbsp;&nbsp;&nbsp;2、log4j &nbsp;&nbsp;&nbsp;&nbsp;3、jboss-marshalling &nbsp;&nbsp; jboss-marshalling-serial 需要jar包的可以去我的github下载或者自己去官网下载。<a href="https://github.com/hfbin/Thread_Socket/tree/master/Socket/runtime/jar%E5%8C%85" target="_blank" rel="external">https://github.com/hfbin/Thread_Socket/tree/master/Socket/runtime/jar%E5%8C%85</a></p>
<p>还是老规矩有实体类先上实体类</p>
<h5 id="2-1-实体类"><a href="#2-1-实体类" class="headerlink" title="2.1 实体类"></a><strong>2.1 实体类</strong></h5><p> 首先，需要两个实体类，实体类都需要实现Serializable接口，Request类是用来做客户端的请求的， Response类是用来做服务端返回给客户端的响应。</p>
<p> Request<br> <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Request</span> <span class="keyword">implements</span> <span class="title">Serializable</span></span>&#123;</div><div class="line"></div><div class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span>  SerialVersionUID = <span class="number">1L</span>;</div><div class="line">	</div><div class="line">	<span class="keyword">private</span> String id ;</div><div class="line">	<span class="keyword">private</span> String name ;</div><div class="line">	<span class="keyword">private</span> String requestMessage ;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getId</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">return</span> id;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(String id)</span> </span>&#123;</div><div class="line">		<span class="keyword">this</span>.id = id;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">return</span> name;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">		<span class="keyword">this</span>.name = name;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getRequestMessage</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">return</span> requestMessage;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setRequestMessage</span><span class="params">(String requestMessage)</span> </span>&#123;</div><div class="line">		<span class="keyword">this</span>.requestMessage = requestMessage;</div><div class="line">	&#125;</div><div class="line"></div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>Response</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Response</span> <span class="keyword">implements</span> <span class="title">Serializable</span></span>&#123;</div><div class="line">	</div><div class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">1L</span>;</div><div class="line">	</div><div class="line">	<span class="keyword">private</span> String id;</div><div class="line">	<span class="keyword">private</span> String name;</div><div class="line">	<span class="keyword">private</span> String responseMessage;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getId</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">return</span> id;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(String id)</span> </span>&#123;</div><div class="line">		<span class="keyword">this</span>.id = id;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">return</span> name;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">		<span class="keyword">this</span>.name = name;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getResponseMessage</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">return</span> responseMessage;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setResponseMessage</span><span class="params">(String responseMessage)</span> </span>&#123;</div><div class="line">		<span class="keyword">this</span>.responseMessage = responseMessage;</div><div class="line">	&#125;</div><div class="line">	</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这里代码没什么好说的</p>
<h5 id="2-2-Jboss-Marshalling-编解码工具类"><a href="#2-2-Jboss-Marshalling-编解码工具类" class="headerlink" title="2.2 Jboss Marshalling 编解码工具类"></a><strong>2.2 Jboss Marshalling 编解码工具类</strong></h5><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">MarshallingCodeCFactory</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 创建Jboss Marshalling解码器MarshallingDecoder</span></div><div class="line"><span class="comment">     * <span class="doctag">@return</span> MarshallingDecoder</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> MarshallingDecoder <span class="title">buildMarshallingDecoder</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="comment">//1</span></div><div class="line">        <span class="keyword">final</span> MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory(<span class="string">"serial"</span>);</div><div class="line">        <span class="comment">//2</span></div><div class="line">        <span class="keyword">final</span> MarshallingConfiguration configuration = <span class="keyword">new</span> MarshallingConfiguration();</div><div class="line">        configuration.setVersion(<span class="number">5</span>);</div><div class="line">        <span class="comment">//3</span></div><div class="line">        UnmarshallerProvider provider = <span class="keyword">new</span> DefaultUnmarshallerProvider(marshallerFactory, configuration);</div><div class="line">        <span class="comment">//4</span></div><div class="line">        MarshallingDecoder decoder = <span class="keyword">new</span> MarshallingDecoder(provider, <span class="number">1024</span> * <span class="number">1024</span> * <span class="number">1</span>);</div><div class="line">        <span class="keyword">return</span> decoder;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 创建Jboss Marshalling编码器MarshallingEncoder</span></div><div class="line"><span class="comment">     * <span class="doctag">@return</span> MarshallingEncoder</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> MarshallingEncoder <span class="title">buildMarshallingEncoder</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">final</span> MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory(<span class="string">"serial"</span>);</div><div class="line">        <span class="keyword">final</span> MarshallingConfiguration configuration = <span class="keyword">new</span> MarshallingConfiguration();</div><div class="line">        configuration.setVersion(<span class="number">5</span>);</div><div class="line">        MarshallerProvider provider = <span class="keyword">new</span> DefaultMarshallerProvider(marshallerFactory, configuration);</div><div class="line">        <span class="comment">//5</span></div><div class="line">        MarshallingEncoder encoder = <span class="keyword">new</span> MarshallingEncoder(provider);</div><div class="line">        <span class="keyword">return</span> encoder;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>1、首先通过Marshalling工具类的精通方法获取Marshalling实例对象 参数serial标识创建的是java序列化工厂对象。</p>
<p>2、创建了MarshallingConfiguration对象，配置了版本号为5</p>
<p>3、根据marshallerFactory和configuration创建provider</p>
<p>4、构建Netty的MarshallingDecoder对象，俩个参数分别为provider和单个消息序列化后的最大长度</p>
<p>5、构建Netty的MarshallingEncoder对象，MarshallingEncoder用于实现序列化接口的POJO对象序列化为二进制数组</p>
<p>个人感觉不难都是一些固定的写法，记住每一步要做什么就好。</p>
<h5 id="2-3-服务端"><a href="#2-3-服务端" class="headerlink" title="2.3 服务端"></a><strong>2.3 服务端</strong></h5><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Server</span> </span>&#123;</div><div class="line"></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception</span>&#123;</div><div class="line">		</div><div class="line">		EventLoopGroup pGroup = <span class="keyword">new</span> NioEventLoopGroup();</div><div class="line">		EventLoopGroup cGroup = <span class="keyword">new</span> NioEventLoopGroup();</div><div class="line">		</div><div class="line">		ServerBootstrap b = <span class="keyword">new</span> ServerBootstrap();</div><div class="line">		b.group(pGroup, cGroup)</div><div class="line">		 .channel(NioServerSocketChannel.class)</div><div class="line">		 .option(ChannelOption.SO_BACKLOG, <span class="number">1024</span>)</div><div class="line">		 <span class="comment">//1</span></div><div class="line">		 .handler(<span class="keyword">new</span> LoggingHandler(LogLevel.INFO))</div><div class="line">		 .childHandler(<span class="keyword">new</span> ChannelInitializer&lt;SocketChannel&gt;() &#123;</div><div class="line">			<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(SocketChannel sc)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">			    <span class="comment">//2</span></div><div class="line">				sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());</div><div class="line">				<span class="comment">//3</span></div><div class="line">				sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());</div><div class="line">				<span class="comment">//4</span></div><div class="line">				sc.pipeline().addLast(<span class="keyword">new</span> ReadTimeoutHandler(<span class="number">5</span>)); </div><div class="line">				sc.pipeline().addLast(<span class="keyword">new</span> ServerHandler());</div><div class="line">			&#125;</div><div class="line">		&#125;);</div><div class="line">		</div><div class="line">		ChannelFuture cf = b.bind(<span class="number">8765</span>).sync();</div><div class="line">		</div><div class="line">		cf.channel().closeFuture().sync();</div><div class="line">		pGroup.shutdownGracefully();</div><div class="line">		cGroup.shutdownGracefully();</div><div class="line">		</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>1、设置日志（这里需要自己导入log4j.jar） 当然你也可以不设置打印日记</p>
<p>2、这是我们写的Jboss Marshalling工具类的解码器MarshallingDecoder</p>
<p>3、这是我们写的Jboss Marshalling工具类的编码器MarshallingEncoder </p>
<p>4、超时handler（当服务器端与客户端在指定时间以上没有任何进行通信，则会关闭响应的通道，主要为减小服务端资源占用）单位是秒</p>
<p>其他不懂的去看我Netty的第一篇文章</p>
<h5 id="2-4-服务端业务逻辑"><a href="#2-4-服务端业务逻辑" class="headerlink" title="2.4 服务端业务逻辑"></a><strong>2.4 服务端业务逻辑</strong></h5><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ServerHandler</span> <span class="keyword">extends</span> <span class="title">ChannelHandlerAdapter</span></span>&#123;</div><div class="line"></div><div class="line">	<span class="meta">@Override</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line"></div><div class="line">	&#125;</div><div class="line"></div><div class="line">	<span class="meta">@Override</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">		Request request = (Request)msg;</div><div class="line">		System.out.println(<span class="string">"Server : "</span> + request.getId() + <span class="string">", "</span> + request.getName() + <span class="string">", "</span> + request.getRequestMessage());</div><div class="line">		Response response = <span class="keyword">new</span> Response();</div><div class="line">		response.setId(request.getId());</div><div class="line">		response.setName(<span class="string">"response"</span> + request.getId());</div><div class="line">		response.setResponseMessage(<span class="string">"响应内容"</span> + request.getId());</div><div class="line">		ctx.writeAndFlush(response);<span class="comment">//.addListener(ChannelFutureListener.CLOSE);</span></div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这里业务逻辑主要是将客户端传过来的信息进行打印，然后将数据传入返回的实体类Response，将实体类Response返回给客户端</p>
<h5 id="2-5-客户端"><a href="#2-5-客户端" class="headerlink" title="2.5 客户端"></a><strong>2.5 客户端</strong></h5><p>上面的那些代码之前案例我都写过，基本上没什么变化，只有客户端的代码变化最大，下面来一一说明。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Client</span> </span>&#123;</div><div class="line">	</div><div class="line">    <span class="comment">// 1</span></div><div class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">SingletonHolder</span> </span>&#123;</div><div class="line">		<span class="keyword">static</span> <span class="keyword">final</span> Client instance = <span class="keyword">new</span> Client();</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Client <span class="title">getInstance</span><span class="params">()</span></span>&#123;</div><div class="line">		<span class="keyword">return</span> SingletonHolder.instance;</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	<span class="keyword">private</span> EventLoopGroup group;</div><div class="line">	<span class="keyword">private</span> Bootstrap b;</div><div class="line">	<span class="keyword">private</span> ChannelFuture cf ;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">private</span> <span class="title">Client</span><span class="params">()</span></span>&#123;</div><div class="line">			group = <span class="keyword">new</span> NioEventLoopGroup();</div><div class="line">			b = <span class="keyword">new</span> Bootstrap();</div><div class="line">			b.group(group)</div><div class="line">			 .channel(NioSocketChannel.class)</div><div class="line">			 .handler(<span class="keyword">new</span> LoggingHandler(LogLevel.INFO))</div><div class="line">			 .handler(<span class="keyword">new</span> ChannelInitializer&lt;SocketChannel&gt;() &#123;</div><div class="line">					<span class="meta">@Override</span></div><div class="line">					<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(SocketChannel sc)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">					    <span class="comment">//2</span></div><div class="line">						sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());</div><div class="line">						<span class="comment">//3</span></div><div class="line">						sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());</div><div class="line">						<span class="comment">//4</span></div><div class="line">						sc.pipeline().addLast(<span class="keyword">new</span> ReadTimeoutHandler(<span class="number">5</span>)); </div><div class="line">						sc.pipeline().addLast(<span class="keyword">new</span> ClientHandler());</div><div class="line">					&#125;</div><div class="line">		    &#125;);</div><div class="line">	&#125;</div><div class="line">	<span class="comment">//5</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">connect</span><span class="params">()</span></span>&#123;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			<span class="keyword">this</span>.cf = b.connect(<span class="string">"127.0.0.1"</span>, <span class="number">8765</span>).sync();</div><div class="line">			System.out.println(<span class="string">"远程服务器已经连接, 可以进行数据交换.."</span>);				</div><div class="line">		&#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">			e.printStackTrace();</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	<span class="comment">//6</span></div><div class="line">	<span class="function"><span class="keyword">public</span> ChannelFuture <span class="title">getChannelFuture</span><span class="params">()</span></span>&#123;</div><div class="line">		<span class="comment">//如果没有连接先链接</span></div><div class="line">		<span class="keyword">if</span>(<span class="keyword">this</span>.cf == <span class="keyword">null</span>)&#123;</div><div class="line">			<span class="keyword">this</span>.connect();</div><div class="line">		&#125;</div><div class="line">		<span class="comment">//this.cf.channel().isActive() 这里得到的是链接状态 在重新连接时候使用的 返回true/false</span></div><div class="line">		<span class="keyword">if</span>(!<span class="keyword">this</span>.cf.channel().isActive())&#123;</div><div class="line">			<span class="keyword">this</span>.connect();</div><div class="line">		&#125;</div><div class="line">		<span class="keyword">return</span> <span class="keyword">this</span>.cf;</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception</span>&#123;</div><div class="line">		<span class="keyword">final</span> Client c = Client.getInstance();</div><div class="line">		<span class="comment">//c.connect();</span></div><div class="line">		ChannelFuture cf = c.getChannelFuture();</div><div class="line">		<span class="comment">//7</span></div><div class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= <span class="number">3</span>; i++ )&#123;</div><div class="line">			Request request = <span class="keyword">new</span> Request();</div><div class="line">			request.setId(<span class="string">""</span> + i);</div><div class="line">			request.setName(<span class="string">"pro"</span> + i);</div><div class="line">			request.setRequestMessage(<span class="string">"数据信息"</span> + i);</div><div class="line">			cf.channel().writeAndFlush(request);</div><div class="line">			TimeUnit.SECONDS.sleep(<span class="number">4</span>);</div><div class="line">		&#125;</div><div class="line">        <span class="comment">//8</span></div><div class="line">		cf.channel().closeFuture().sync();</div><div class="line">		</div><div class="line">		<span class="comment">//9 重连</span></div><div class="line">		<span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable() &#123;</div><div class="line">			<span class="meta">@Override</span></div><div class="line">			<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">				<span class="keyword">try</span> &#123;</div><div class="line">					System.out.println(<span class="string">"进入子线程..."</span>);</div><div class="line">					<span class="comment">//重新调用连接</span></div><div class="line">					ChannelFuture cf = c.getChannelFuture();</div><div class="line">					System.out.println(cf.channel().isActive());</div><div class="line">					System.out.println(cf.channel().isOpen());</div><div class="line">					</div><div class="line">					<span class="comment">//再次发送数据</span></div><div class="line">					Request request = <span class="keyword">new</span> Request();</div><div class="line">					request.setId(<span class="string">""</span> + <span class="number">4</span>);</div><div class="line">					request.setName(<span class="string">"pro"</span> + <span class="number">4</span>);</div><div class="line">					request.setRequestMessage(<span class="string">"数据信息"</span> + <span class="number">4</span>);</div><div class="line">					cf.channel().writeAndFlush(request);					</div><div class="line">					cf.channel().closeFuture().sync();</div><div class="line">					System.out.println(<span class="string">"子线程结束."</span>);</div><div class="line">				&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</div><div class="line">					e.printStackTrace();</div><div class="line">				&#125;</div><div class="line">			&#125;</div><div class="line">		&#125;).start();</div><div class="line">		</div><div class="line">		System.out.println(<span class="string">"断开连接,主线程结束.."</span>);</div><div class="line">		</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>还是老规矩，在这我只对一些重要的做说明：</p>
<p>1、为了保证线安全我采用了单例模式，构造静态内部类实现单例模式，在这不懂的可以看我的这篇<a href="http://blog.csdn.net/qq_33524158/article/details/78566403" target="_blank" rel="external">文章</a></p>
<p>2、这是我们写的Jboss Marshalling工具类的解码器MarshallingDecoder</p>
<p>3、这是我们写的Jboss Marshalling工具类的编码器MarshallingEncoder </p>
<p>4、超时handler（当服务器端与客户端在指定时间以上没有任何进行通信，则会关闭响应的通道，主要为减小服务端资源占用）单位是秒</p>
<p>5、connect()这里我单独抽出一个方法来做服务器连接的</p>
<p>6、getChannelFuture()这个方法主要是为了超时时候做的，也就简单的调用了连接的方法</p>
<p>7、每隔四秒发送一条数据给服务端，注意这里插完三条数据后超过五秒（看4）后没有给服务端发送数据就会进入重连状态</p>
<p>8、等待关闭</p>
<p>9、重连，里面的代码很简单，我就不做说明了</p>
<h5 id="2-6-客户端业务逻辑"><a href="#2-6-客户端业务逻辑" class="headerlink" title="2.6 客户端业务逻辑"></a><strong>2.6 客户端业务逻辑</strong></h5><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClientHandler</span> <span class="keyword">extends</span> <span class="title">ChannelHandlerAdapter</span></span>&#123;</div><div class="line">	</div><div class="line">	<span class="meta">@Override</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line"></div><div class="line">	&#125;</div><div class="line"></div><div class="line">	<span class="meta">@Override</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			Response resp = (Response)msg;</div><div class="line">			System.out.println(<span class="string">"Client : "</span> + resp.getId() + <span class="string">", "</span> + resp.getName() + <span class="string">", "</span> + resp.getResponseMessage());			</div><div class="line">		&#125; <span class="keyword">finally</span> &#123;</div><div class="line">			ReferenceCountUtil.release(msg);</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这里很简单，没什么好说的了。</p>
<p>好！到这目前所有代码都编写完了来测试一下效果。</p>
<p>服务端启动打印如图：</p>
<p><img src="http://img.blog.csdn.net/20171127004448326?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzM1MjQxNTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"></p>
<p>客户端启动打印如图： </p>
<p><img src="http://img.blog.csdn.net/20171127004459063?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzM1MjQxNTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"></p>
<p>客户端启动后服务端的打印：</p>
<p><img src="http://img.blog.csdn.net/20171127004512265?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzM1MjQxNTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="这里写图片描述"></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;这里只看几张照片是看不出什么效果的，建议下载源码，自己测试，注意看打印结果。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;好代码说完了，运行结果也看了，刚刚留的两个问题现在可以说一下了，为了大家方便我重新说一下要解决的两个问题。</p>
<p>1、如何在超时（即服务器和客户端没有任何通信）后关闭通道？关闭通道后我们又如何再次建立连接？</p>
<p>2、客户端宕机时，我们无需考虑，下次客户端重启之后我们就可以与服务器建立连接，但是服务器宕机时，我们的客户端如何与服务器进行连接呢？</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;第一个问题，相信大家都知道如何解决的了，在客户端跟服务端都使用了Netty提供的超时方法ReadTimeoutHandler(5)，参数是以秒来算的。关闭通道后我们重新启动一个线程调用getChannelFuture()方法。重新连接。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;第二个问题，首先我们肯定的是在liunx环境下做部署的，我们可以在liunx下编写启动服务端的脚本（.sh），要是服务端真出问题只需要启动脚本就可以启动服务器了。</p>
<p>好！到这这个案例就讲解完了，下一篇文章是Netty实战的第二个使用场景。</p>
<p>源代码：<a href="https://github.com/hfbin/Thread_Socket/tree/master/Socket/runtime" target="_blank" rel="external">https://github.com/hfbin/Thread_Socket/tree/master/Socket/runtime</a></p>
<p>转发者必须注明转发链接</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>Donate</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weixinpay.png" alt="HuangFuBin WeChat Pay"/>
        <p>WeChat Pay</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="HuangFuBin Alipay"/>
        <p>Alipay</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" <i class="fa fa-tag"></i> java</a>
          
            <a href="/tags/网络编程/" <i class="fa fa-tag"></i> 网络编程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/11/24/java网络编程之Netty编解码技术（六）/" rel="next" title="java网络编程之Netty编解码技术（六）">
                <i class="fa fa-chevron-left"></i> java网络编程之Netty编解码技术（六）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/11/27/java网络编程之Netty实战心跳检测（八）/" rel="prev" title="java网络编程之Netty实战心跳检测（八）">
                java网络编程之Netty实战心跳检测（八） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_tsina"></a>
  <!--<a class="jiathis_button_tqq"></a>-->
  
  <!--<a class="jiathis_button_douban"></a>-->
  <!--<a class="jiathis_button_renren"></a>-->
  <a class="jiathis_button_qzone"></a>
  <!--<a class="jiathis_button_kaixin001"></a>-->
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://avatars3.githubusercontent.com/u/26451830?s=400&u=fac2b4c7903b3ad1210b530e2d18e42fcb410b0a&v=4"
               alt="HuangFuBin" />
          <p class="site-author-name" itemprop="name">HuangFuBin</p>
           
              <p class="site-description motion-element" itemprop="description">My friend promised me to go if I had the road</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">107</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">28</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">37</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hfbin" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=DmZ7b2BpaHtsZ2AgbGF9fU5oYXZjb2diIG1hYw" target="_blank" title="E-Mail">
                  
                    <i class="fa fa-fw fa-envelope"></i>
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/3904243687/profile?rightmod=1&wvr=6&mod=personinfo&is_all=1" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                    
                      Weibo
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.hfbin.cn/" title="Title" target="_blank">Title</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#undefined"><span class="nav-number">1.</span> <span class="nav-text">Netty最佳实战数据通信</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-分析"><span class="nav-number">1.1.</span> <span class="nav-text">1 分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-案例"><span class="nav-number">1.2.</span> <span class="nav-text">2 案例</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#2-1-实体类"><span class="nav-number">1.2.1.</span> <span class="nav-text">2.1 实体类</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-Jboss-Marshalling-编解码工具类"><span class="nav-number">1.2.2.</span> <span class="nav-text">2.2 Jboss Marshalling 编解码工具类</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-3-服务端"><span class="nav-number">1.2.3.</span> <span class="nav-text">2.3 服务端</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-4-服务端业务逻辑"><span class="nav-number">1.2.4.</span> <span class="nav-text">2.4 服务端业务逻辑</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-5-客户端"><span class="nav-number">1.2.5.</span> <span class="nav-text">2.5 客户端</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-6-客户端业务逻辑"><span class="nav-number">1.2.6.</span> <span class="nav-text">2.6 客户端业务逻辑</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <!--
<div class="copyright display_zhanzhang" style="text-align: center !important;">
  <span class="author" itemprop="copyrightHolder">桂ICP备16010161号</span>
</div>
-->
<div class="copyright" style="text-align: center !important;">
  
  &copy;  2017 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HuangFuBin</span>
</div>
<div class="copyright" style="text-align: center !important;">
	
	<div class="powered-by" style="text-align: center !important;">
	  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
	</div>

	<div class="theme-info" style="text-align: center !important;">
	  主题 -
	  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
		NexT.Mist
	  </a>
	</div>
	
</div>
<div class="copyright display_zhanzhang"  style="text-align: center !important;">
<script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1266987503'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s19.cnzz.com/z_stat.php%3Fid%3D1266987503%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>
        

<div class="busuanzi-count">
  

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cysX5MNF0';
      var conf = '504c8a8b8a5aff5f06dd805c527bbf0f';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  




  
  
  
  <link rel="stylesheet" href="/lib/algolia-instant-search/instantsearch.min.css">

  
  
  <script src="/lib/algolia-instant-search/instantsearch.min.js"></script>
  

  <script src="/js/src/algolia-search.js?v=5.1.2"></script>



  

  

  

  

  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.2"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.2"></script>


  

  <!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>
</body>

</html>
